'''
    @project: Masdevallia
    @author: Austin Baker
    @created: 2/22/2014
    @license: http://opensource.org/licenses/mit-license.php

    The MIT License (MIT)

    Copyright (c) 2014 Austin Baker
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    
    ------
    
    About:
'''

import maya.OpenMaya as OpenMaya

import masdevallia.meta.BaseMeta as BaseMeta
import masdevallia.utility.Dag as Dag

class RigMeta( BaseMeta.BaseMeta ):
    def __init__( self, node_name=None ):
        super( RigMeta, self ).__init__( node_name=node_name, node_type='RigMeta' )
        
    def initAttributes( self ):
        '''
        Default attributes for this node.
        '''
        super( RigMeta, self ).initAttributes()
        dep_fn = OpenMaya.MFnDependencyNode()
        dep_fn.setObject( self.mobject )
        
        # Meta children.
        children_str_attr = OpenMaya.MFnTypedAttribute()
        children_obj = children_str_attr.create( 'metaChildren', 'metaChildren', OpenMaya.MFnData.kString )
        children_str_attr.setArray( True )
        dep_fn.addAttribute( children_obj )
        
    def addChildMeta( self, source_plug ):
        '''
        This is an array plug so we need to handle connecting to it differently.
        We use logical index to create a new element. We also need to set some 
        data on the newly created element otherwise Maya won't physically create
        the element.
        
        @param source_plug: MPlug.
        '''
        dep_fn = OpenMaya.MFnDependencyNode( self.mobject )
        children_plugs = dep_fn.findPlug( 'metaChildren' )
        children_elements = children_plugs.numElements()
        
        # Check if the source plug is already connected.
        for plug_idx in xrange( children_elements ):
            plug = children_plugs[ plug_idx ]            
            connected_plugs = Dag.getPlugConnections( plug, True, False )
            for connected_idx in xrange( connected_plugs.length() ):
                connected_plug = connected_plugs[ connected_idx ]
                if connected_plug.name() == source_plug.name():
                    # Already connected. Get out of the function.
                    OpenMaya.MGlobal.displayInfo( '{0} is already connected to {1}'.format( source_plug.name(), plug.name() ) ) 
                    return
        
        # Make the new element plug.
        destination_plug = children_plugs.elementByLogicalIndex( children_elements )
        
        # Do the connection.
        MDGMod = OpenMaya.MDGModifier()
        MDGMod.connect( source_plug, destination_plug )
        MDGMod.doIt()
        
    def getMetaNodes( self ):
        '''
        Returns a list of all meta nodes associated with this rig.
        '''
        results = []
        
        dep_fn = OpenMaya.MFnDependencyNode( self.mobject )
        children_plugs = dep_fn.findPlug( 'metaChildren' )
        
        for plug_idx in xrange( children_plugs.numElements() ):
            plug = children_plugs[ plug_idx ]
            connected_plugs = Dag.getPlugConnections( plug, True, False )
            
            for connected_idx in xrange( connected_plugs.length() ):
                connected_plug = connected_plugs[ connected_idx ]
                node = connected_plug.node()
                type_plug = Dag.getPlugByName( node, 'metaType' )
                
                type_name = type_plug.asString()
                node_name = connected_plug.asString()                
                new_class = globals()[ type_name ]
                results.append( new_class( node_name=node_name ) )
        
        return results